package com.cqc.fragmentreplace.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import com.cqc.fragmentreplace.R;
import com.cqc.fragmentreplace.fragment.Frag1;
import com.cqc.fragmentreplace.fragment.Frag2;
import com.cqc.fragmentreplace.fragment.Frag3;
import com.cqc.fragmentreplace.fragment.Frag4;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ${cqc} on 2017/9/8.
 */

public class AddHideShowActivity2 extends AppCompatActivity {

    @BindView(R.id.btn1)
    Button btn1;
    @BindView(R.id.btn2)
    Button btn2;
    @BindView(R.id.btn3)
    Button btn3;
    @BindView(R.id.btn4)
    Button btn4;
    @BindView(R.id.frame)
    FrameLayout frame;

    private int oldPosition = 0;//默认上一个Fragment是 frags[0]
    private List<Fragment> frags = new ArrayList<>();//Fragment集合
    private FragmentManager fm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_hide);
        ButterKnife.bind(this);
        fm = getSupportFragmentManager();
        initFrags();
        switchFragment(0);
    }

    private void initFrags() {
        frags.add(new Frag1());
        frags.add(new Frag2());
        frags.add(new Frag3());
        frags.add(new Frag4());
    }

    @OnClick({R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn1:
                switchFragment(0);
                break;
            case R.id.btn2:
                switchFragment(1);
                break;
            case R.id.btn3:
                switchFragment(2);
                break;
            case R.id.btn4:
                switchFragment(3);
                break;
        }
    }

    private void switchFragment(int position) {
        if (position >= frags.size()) {
            return;
        }
        Fragment newFrag = frags.get(position);
        Fragment oldFrag = frags.get(oldPosition);
        oldPosition = position;
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.hide(oldFrag);
        if (!newFrag.isAdded()) {
            transaction.add(R.id.frame, newFrag);
        }
        transaction.show(newFrag);
        transaction.commitAllowingStateLoss();
    }
}
